import React, { useState, useRef, useContext, useEffect } from "react";
import { Form, Input } from 'antd';
import { EditableContext } from "./editableTable";

export default ({ title, editable, children, dataIndex, record, handleSave, ...restProps }: any) => {
    const [editing, setEditing] = useState(false);
    const inputRef: any = useRef();
    const form = useContext(EditableContext);

    useEffect(() => {
        if (editing) {
            inputRef.current.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };
    const save = async (e: any) => {
        try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({ ...record, ...values });
        } catch (err) {
            console.error(err);
        }
    };

    let childNode = children;
    if (editable) {
        childNode = editing ? (
            <Form.Item style={{ margin: 0 }} name={dataIndex} rules={[{ required: true, message: '请输入' }]}>
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div onClick={toggleEdit}>{children}</div>
        );
    }

    return <td {...restProps}>{childNode}</td>;
};
